/**
 * 2009-10-28 下午05:02:30 
 * esignature
 * com.smc.action.user
 * UserAction
 */
package com.smc.action.user;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.smc.common.constants.RoleConstant;
import com.smc.domain.model.Hospital;
import com.smc.domain.model.User;
import com.smc.security.Authentication;
import com.smc.security.AuthenticationManager;
import com.smc.security.GrantedAuthority;
import com.smc.security.SecurityContextHolder;
import com.smc.security.util.CoderUtil;
import com.smc.server.AuthenticationService;
import com.smc.server.UserService;

/**
 * @author chenheng
 * @version 0.0.1
 * 表现层用户操作
 */
public class UserAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = -6365912447595265173L;
	/**
	 * 每次读取文件大小
	 */
	private static final int BUFFER_SIZE = 16 * 1024 ;
	/**
	 * 业务层用户服务
	 */
	private UserService userService ;
	/**
	 * 认证授权管理器
	 */
	private AuthenticationManager authenticationManager ;
	/**
	 * 业务层权限服务
	 */
	private AuthenticationService authenticationService ;
	/**
	 * 表现层Request对象
	 */
	private HttpServletRequest request ;
	/**
	 * 表现层Response对象
	 */
	private HttpServletResponse response ;
	/**
	 * 用户
	 */
	private User user ;
	/**
	 * 菜单列表
	 */
	private List<Menu> menuList = new ArrayList<Menu>();
	/**
	 * 医院列表
	 */
	private List<Hospital> hospitalList ;
	/**
	 * 上传头相
	 */
	private File headerIcon ;
	/**
	 * 图片类型
	 */
	private String contentType ;
	/**
	 * 文件名
	 */
	private String fileName ;
	
	private String birthday ;
	private String oldPassword ;
	private String newPassword ;
	private String confirmPassword ;
	
	//////////////////////////////////////////////////////////////////////////////////////////
	////////////// 属性的基本setter 、getter方法	//////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////
	public void setServletRequest(HttpServletRequest request) {
		this.request = request ;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}
	
	
	public AuthenticationService getAuthenticationService() {
		return authenticationService;
	}

	public void setAuthenticationService(AuthenticationService authenticationService) {
		this.authenticationService = authenticationService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public List<Menu> getMenuList() {
		return menuList;
	}

	public void setMenuList(List<Menu> menuList) {
		this.menuList = menuList;
	}
	
	public List<Hospital> getHospitalList() {
		return hospitalList;
	}

	public void setHospitalList(List<Hospital> hospitalList) {
		this.hospitalList = hospitalList;
	}
	
	
	public String getHeaderIconContentType() {
		return contentType;
	}

	public void setHeaderIconContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getHeaderIconFileName() {
		return fileName;
	}

	public void setHeaderIconFileName(String fileName) {
		this.fileName = fileName;
	}

	public File getHeaderIcon() {
		return headerIcon;
	}

	public void setHeaderIcon(File headerIcon) {
		this.headerIcon = headerIcon;
	}
	
	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	
	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	//////////////////////////////////////////////////////////////////////////////////////////
	//////////////////	表现层控制方法		//////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * 登陆
	 */
	public String login() {
		try {
			authenticationManager.usernamePasswordAuthentication(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		if ( SecurityContextHolder.getAuthentication(request.getSession()).isAuthenticated()) {
			return SUCCESS ;
		} else {
			return INPUT ;
		}
	}
	/**
	 * 注销
	 * @return
	 */
	public String logout() {
		authenticationManager.logout(request, response);
		return SUCCESS;
	}
	/**
	 * 用户注册
	 * @return
	 * @throws Throwable 
	 * 
	 */
	public String register() throws Throwable {
		User u = userService.fetch_IG_IG_IG_user(user.getUsername());
		if ( u != null ) {
			this.addFieldError("user.username", "The username is existed,please change other name !");
			return INPUT ;
		}
		String password = CoderUtil.byte2hex(CoderUtil.encryptMD5((user.getUsername() + user.getPassword()).getBytes()));
		user.setPassword(password);
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		java.sql.Date d = new java.sql.Date(format.parse(birthday).getTime());
		user.setBirthday(d);
		userService.save_IG_IG_IG_user(user);
		return SUCCESS ;
	}
	public String getUserByUuid() {
		String uuid = (String) SecurityContextHolder.getAuthentication(request.getSession()).getUUUID();
		user = userService.fetch_IG_IG_FE_user(uuid);
		return SUCCESS ;
	}
	public String updateUser() throws Exception {
		if ( !oldPassword.trim().equals("") && !newPassword.trim().equals("") && !confirmPassword.trim().equals("")) {
			String encodeOldPass = CoderUtil.byte2hex(CoderUtil.encryptMD5((user.getUsername() + oldPassword).getBytes()));
			User u = userService.login_IG_IG_IG_user(user.getUsername(), encodeOldPass);
			if ( u == null) {
				this.addFieldError("oldPassword", "Old Password Error");
				return INPUT ;
			}
			if ( newPassword != confirmPassword ){
				this.addFieldError("confirmPassword", "The New Password And the Confirm Password are not identical");
				return INPUT ;
			}
			String encodeNewPass = CoderUtil.byte2hex(CoderUtil.encryptMD5((user.getUsername() + newPassword).getBytes()));
			user.setPassword(encodeNewPass);
		}
			
		userService.update_IG_IG_SA_user(user);
		return SUCCESS ;
	}
	public String usernameExisted() {
		String username = request.getParameter("username");
		user = userService.fetch_IG_IG_IG_user(username);
		return SUCCESS ;
	}
	public String updateHeaderIcon() {
		DateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		String formatStr = df.format(new Date());
		String extension = fileName.substring(fileName.lastIndexOf("."));
		String headerIconName = "header_icon_" + formatStr + extension ;
		saveHeaderIcon(headerIconName);
		userService.save_IG_US_SA_user(user.getUuid(), headerIconName);
		return SUCCESS;
	}
	public List<Hospital> initHospital() {
		hospitalList = userService.fetch_IG_IG_IG_hospital();
		return hospitalList;
	}
	public boolean saveHeaderIcon(String headerIconName) {
		boolean flag = false ;
		InputStream in = null ;
		OutputStream out = null ;
		try {
			in = new BufferedInputStream(new FileInputStream(headerIcon),BUFFER_SIZE);
			String outputFolder = userService.get_IG_IG_IG_HeaderIconPath() + user.getUsername();
			File outputFile = new File(outputFolder);
			if ( ! outputFile.exists()) {
				outputFile.mkdir();
			}
			out = new BufferedOutputStream(new FileOutputStream(new File(outputFolder + "/" + headerIconName)),BUFFER_SIZE) ;
			byte[] buffer = new byte[BUFFER_SIZE];
			while ( in.read(buffer) > 0 ) {
				out.write(buffer);
			}
			flag = true ;
		} catch (Exception ex ) {
			ex.printStackTrace();
		} finally {
			if ( null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if ( null != out) {
				try {
					out.close() ;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag ;
	}
	
	/**
	 * 初始化菜单
	 * @return
	 */
	public String initMenu() {
		//取得当前用户的认证授权信息，根据用户具有的角色初始化菜单的内容
		Authentication auth = SecurityContextHolder.getAuthentication(request.getSession());
		if (auth != null ) {
			boolean roleAdminExisted = false ;
			boolean roleHospitalExisted = false ;
			boolean roleUserExisted = false ;
			boolean roleOperateExisted = false ;
			for ( GrantedAuthority ga : auth.getAuthorities()) {
				com.smc.domain.model.Authentication a = ga.getAuthority() ;
				if ( ! roleAdminExisted && (a.getRole() & RoleConstant.ROLE_ADMIN ) > 0 ) {
					Menu m1 = new Menu("User Manager","",0);
					Menu m2 = new Menu("Verify User","listUnVerifiedUser.shtml",1);
					Menu m3 = new Menu("List User","listUser.shtml",1);
					Menu m4 = new Menu("Search User","preSearchUser.shtml",1);
					Menu m5 = new Menu("Hospital Manager","",0);
					Menu m6 = new Menu("Add Hospital","preAddHospital.shtml",1);
					Menu m7 = new Menu("List Hospital","listHospital.shtml",1);
					Menu m8 = new Menu("Certificate Manager","",0);
					Menu m9 = new Menu("Apply Certificate List","listApplyCert.shtml",1);
					Menu m10 = new Menu("Authorited Certificate List","listAuthCert.shtml",1);
					menuList.add(m1);
					menuList.add(m2);
					menuList.add(m3);
					menuList.add(m4);
					menuList.add(m5);
					menuList.add(m6);
					menuList.add(m7);
					menuList.add(m8);
					menuList.add(m9);
					menuList.add(m10);
					roleAdminExisted = true ;
				}
				if ( ! roleHospitalExisted && (a.getRole() & RoleConstant.ROLE_HOSPITAL) > 0 ) {
					Menu m1 = new Menu("Hospital Manager","",0);
					Menu m2 = new Menu("Physician List","listPhysicianDocNum.shtml",1);
					Menu m3 = new Menu("Physician Rank","listPhysicianRankDocNum.shtml",1);
					Menu m4 = new Menu("Patient Documents","listPatientDocNum.shtml",1);
					Menu m5 = new Menu("Signed Documents","listSignedHODocument.shtml",1);
					Menu m6 = new Menu("UnSigned Documents","listUnSignedHODocument.shtml",1);
					Menu m7 = new Menu("Search Documents","preSearchDocument.shtml",1);
					menuList.add(m1);
					menuList.add(m2);
					menuList.add(m3);
					menuList.add(m4);
					menuList.add(m5);
					menuList.add(m6);
					menuList.add(m7);
					roleHospitalExisted = true ;
				}
				if ( ! roleOperateExisted && (a.getRole() & RoleConstant.ROLE_OPERATE) > 0 ) {
					Menu m1 = new Menu("Operator Function","",0);
					Menu m2 = new Menu("Original Document List", "listOriginalDocument.shtml",1);
					menuList.add(m1);
					menuList.add(m2);
					roleOperateExisted = true ;
				}
				if ( ! roleUserExisted && (a.getRole() & RoleConstant.ROLE_USER) > 0 ) {
					Menu m1 = new Menu("Document Manager","",0);
					Menu m2 = new Menu("Signed Document List", "listSignedDocument.shtml",1);
					Menu m3 = new Menu("UnSigned Document List", "listUnSignedDocument.shtml",1);
					Menu m4 = new Menu("Certificate Apply","",0);
					Menu m5 = new Menu("Apply Certificate","preApplyCertificate.shtml",1);
					menuList.add(m1);
					menuList.add(m2);
					menuList.add(m3);
					menuList.add(m4);
					menuList.add(m5);
					roleUserExisted = true ;
				}
			}
//			Menu m1 = new Menu("Message Manager","",0);
//			Menu m2 = new Menu("Compose","toCompose.shtml",1);
//			Menu m3 = new Menu("Inbox"," ",1);
//			Menu m4 = new Menu("Sent"," ",1);
//			Menu m5 = new Menu("Friend List"," ",1);
//			Menu m6 = new Menu("Back List"," ",1);
			Menu m7 = new Menu("Personal Manager","",0);
			Menu m8 = new Menu("Edit Personal Info","getUserDetial.shtml",1);
//			menuList.add(m1);
//			menuList.add(m2);
//			menuList.add(m3);
//			menuList.add(m4);
//			menuList.add(m5);
//			menuList.add(m6);
			menuList.add(m7);
			menuList.add(m8);
		}
		return SUCCESS ;
	}
	
	/**
	 * 内部类，菜单对象
	 * @author chenheng
	 * @version 0.0.1
	 */
	class Menu {
		/**
		 * 菜单名
		 */
		String name ;
		/**
		 * 链接
		 */
		String link ;
		/**
		 * 菜单类型： 
		 * 0：表示菜单栏目，不可加链接
		 * 1：表示菜单项，可加链接
		 */
		int type ;
		Menu(String name,String link,int type) {
			this.name = name ;
			this.link = link ;
			this.type = type ;
		}
		public String getLink() {
			return link;
		}
		public void setLink(String link) {
			this.link = link;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getType() {
			return type;
		}
		public void setType(int type) {
			this.type = type;
		}
	}
	
}
